package com.nais.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nais.domain.EcUserInfo;
import com.nais.domain.EcUserInfoCriteria;
import com.nais.domain.EcUsers;
import com.nais.mapper.EcUserInfoMapper;
import com.nais.mapper.EcUsersMapper;
import com.nais.vo.UserFullInfo;

@Service
public class UserInfoService {
	
	@Autowired
	private EcUsersMapper ecUsersMapper;
	
	@Autowired
	private EcUserInfoMapper ecUserInfoMapper;
	
	private static final ConcurrentHashMap<Integer, UserFullInfo> USER_CACHE = new ConcurrentHashMap<>();
	
	private static final Long REFRESH_INTERVAL = Long.valueOf(1 * 60 * 60 * 1000);
	
	
	public UserFullInfo getUserFullInfoById(Integer userId){
		
		UserFullInfo fullUser = USER_CACHE.get(userId);
		if (fullUser != null) {
			
			Long cacheLastReloadTime = fullUser.getLastReloadTime().getTime();
			Long currentReloadTime = new Date().getTime();
			
			if (currentReloadTime - cacheLastReloadTime > REFRESH_INTERVAL) {
				
				UserFullInfo newUser = getUserFromDB(userId);
				USER_CACHE.put(userId, newUser);
				return newUser;
			
			}
			
			return fullUser;
		}
		
		UserFullInfo newUser = getUserFromDB(userId);
		USER_CACHE.put(userId, newUser);
		return newUser;
		
	}
	
	private UserFullInfo getUserFromDB(Integer userId){
		
		EcUsers user = ecUsersMapper.selectByPrimaryKey(userId);
		if (user == null) {
			return null;
		}
		
		UserFullInfo info = new UserFullInfo();
		info.setUsers(user);
		
		EcUserInfoCriteria ecUserInfoCriteria = new EcUserInfoCriteria();
		ecUserInfoCriteria.createCriteria().andUidEqualTo(userId);
		
		List<EcUserInfo> userinfos = ecUserInfoMapper.selectByExample(ecUserInfoCriteria);
		
		if (CollectionUtils.isNotEmpty(userinfos)) {
			info.setUserInfo(userinfos.get(0));
		}
		
		return info;
	}
	
}
